package models

import (
	"time"

	log "github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/pkg/errors"
)

type IpccAppNumbers struct {
	Id           int
	AppId        string    `orm:"column(appid)"`
	Number       string    `orm:"column(number)"`
	Describ      string    `orm:"column(dercrib)"`
	EnterpriseId string    `orm:"column(enterpriseId)"`
	TimeCreate   time.Time `orm:"column(timeCreate)"`
	NumberStatus string    `orm:"column(numberStatus)"`
	RouterAddr   string    `orm:"column(addr)"`
	RouterPort   int       `orm:"column(port)"`
}

func RegIpccNumberManager() {
	orm.RegisterModel(new(IpccAppNumbers))
}

func GetAllActiveNumbersByAppId(appId string, offset int) (*[]IpccAppNumbers, error) {

	result := &[]IpccAppNumbers{}

	o := orm.NewOrm()
	o.Using("default")

	count, err := o.QueryTable(new(IpccAppNumbers)).
		Filter("AppId", appId).
		Filter("NumberStatus", "0").
		Limit(1000, offset*1000).
		All(result)

	if err != nil {
		log.Error("query table err:%v", err)
		return result, err
	}

	if count == 0 {
		err = errors.New("no numbers found")
	}

	return result, err
}

func GetActiveNumbersByAppId(appId string) (*[]IpccAppNumbers, error) {

	result := &[]IpccAppNumbers{}

	o := orm.NewOrm()
	o.Using("default")

	count, err := o.QueryTable(new(IpccAppNumbers)).
		Filter("AppId", appId).
		Filter("NumberStatus", "0").
		All(result)
	if err != nil {
		log.Error("query table err:%v", err)
		return result, err
	}

	if count == 0 {
		err = errors.New("no numbers found")
	}

	return result, err
}
